<template>
    <lay-card>
        <lay-quote size="sm">
            <lay-row space="20">
              <lay-col md="16">
                <lay-tooltip :visible="visible" trigger="click" :content="tips" :isDark="false">
                  <h3>
                    <span>场景组【{{node.dict.scene_name}}】基础信息:</span>
                    <lay-icon size="sm" type="layui-icon-help"></lay-icon>
                  </h3>
                </lay-tooltip>
              </lay-col>
              <lay-col md="8">
                <lay-dropdown updateAtScroll placement="bottom-end" ref="manualRefLeft" :clickOutsideToClose="false">
                  <lay-button size="sm">添加场景</lay-button>
                  <template #content>
                    <div style="width: 500px">
                      <SceneVirtualTree
                        :scrollHeight="'500px'"
                        :showCheckbox="true"
                        @insertTables="insertTables"
                        @cancelCheck="cancelCheckLeft"
                      ></SceneVirtualTree>
                    </div>
                  </template>
                </lay-dropdown>
                <lay-button size="sm" @click="saveScene" type="normal">保存场景组</lay-button>
                <lay-button size="sm" @click="createSql" type="normal">数据生成</lay-button>
              </lay-col>
            </lay-row>
        </lay-quote>
        <lay-row space="10">
          <lay-col md="12"><a>选中的场景：{{ messageTip }}</a></lay-col>
          <lay-col md="12"><a>选中的连线：{{ messageTip2 }}</a></lay-col>
        </lay-row>
        <lay-row space="10">
          <lay-col md="24">
            <lay-dropdown
              ref="manualRef"
              trigger="contextMenu"
              alignPoint
              updateAtScroll
              clickOutsideToClose
            >
                <div id="chart" class="er" style="width: 100%;height:650px"></div>
                <template #content>
                    <lay-dropdown-menu>
                        <lay-dropdown-menu-item
                          v-if="layMode === 1"
                          @click="deleteCurrentScene"
                        >删除此场景</lay-dropdown-menu-item>
                        <lay-dropdown-menu-item
                          v-if="layMode === 2"
                          @click="deleteCurrentLine"
                        >删除关联线</lay-dropdown-menu-item>
                        <lay-line margin="5px" theme="#EEE"></lay-line>
                        <lay-dropdown-menu-item @click="manualRef.hide()">取消(Cancel)</lay-dropdown-menu-item>
                    </lay-dropdown-menu>
                </template>
            </lay-dropdown>
          </lay-col>
        </lay-row>
    </lay-card>
</template>

<script>
export default {
    name: "ErChart",
}
</script>

<script setup>

import {onBeforeUnmount, ref, h, reactive, onMounted} from "vue";

import ErCanvas from "er-canvas";
import {layer} from "@layui/layer-vue";
import {notify} from "../../../../untils/tip";
import {useRoute} from "vue-router";
import {querySceneDetailApi, updateSceneApi} from "../../../../api/module/scene";
import SceneVirtualTree from "../../../../components/scene/tree/SceneVirtualTree.vue";
import ProductData from "../../../../components/scene/data/ProductData.vue";

const messageTip = ref('');
const messageTip2 = ref('');
const route = useRoute();
const node = reactive({dict: {scene_id: '', scene_name: ''}});

onMounted(() => {
    node.dict = route.params;
    createChart([], [])
    querySceneGroupDetail();
})

const visible = ref(false);
const tips = ref('功能：\n1.添加场景，通过连线指定场景间的执行关系；\n2.选定场景名称，右键可设置执行次数；\n3.右键还可删除场景和解除关联关系！');

const manualRef = ref();
const layMode = ref(0);

const i = ref(0);
const index = ref(0);
const chart = ref();

// 记录当前被选中表的位置，大小等属性
const currentTableAttribution = reactive({top: 40, left: 30, width: 300, height: 150})
const currentTable = ref();
const currentLine = ref();

const querySceneGroupDetail = async () => {
  console.log('querySceneGroupDetail:', route.params)
  let {result, status, message} = await querySceneDetailApi({id: node.dict.scene_id, type: 'scene_group'})
  if(status === 'success'){
      node.dict.scene_name = result.name;
      result.tables.forEach((unit)=>{addTableOperate(unit)});
      result.lines.forEach((unit)=>{
          const paramsLine = reactive({form: unit.f, to: unit.t})
          addLineOperate(paramsLine)
      });
  }else {
    layer.msg(message);
  }
};

const createChart = (tables, lines) => {
  chart.value = null;
  console.log('createChart:', tables, lines)
  const operation = reactive({
      width: 1100,
      height: 630,
      grid: true,
      onContextmenu(e, target) {
          if(target&&target.type === 'ErTable'){
            layMode.value = 1;
            currentTable.value = target;
          }else if(target&&target.type === 'ErLine'){
              layMode.value = 2;
              currentLine.value = target;
          }else {
              layMode.value = 0;
          }
          console.log("onContextmenu：", e, target);
          manualRef.value.show();
      },
      onSelectLine(line) {
          console.log("onSelectLine", line);
          if(line){
              messageTip2.value = line.form.options.name + "  --->  " + line.to.options.name;
          }
      },
      onSelectTable(table) {
          console.log("onSelectTable", table);
          if(table?.options?.name){
              messageTip.value = table.options.name;
          }
      },
      tables: tables,
      lines: lines,
  })
  chart.value = new ErCanvas(document.getElementById('chart'), operation);
};

const addTableOperate = (unit) => {
    console.log('addTableOperate:', unit)
    chart.value.addTable(unit);
}

const addLineOperate = (unit) => {
    console.log('addLineOperate: ', unit)
    chart.value.addLine(unit);
}


const deleteCurrentScene = () => {
    if(currentTable.value){
        chart.value.removeTable(currentTable.value.id);
    }else {
        notify('failed', '不存在待删除的场景！')
    }

};

const deleteCurrentLine = () => {
    if(currentLine.value){
        console.log("delete line : ", currentLine.value)
        const line = reactive({form: currentLine.value.options.form, to: currentLine.value.options.to})
        console.log("delete line2 : ", line, chart.value.lines)
        chart.value.removeLine(currentLine.value);
    }else {
        notify('failed', '不存在待删除的连线！')
    }
};


// 插入或更新 依赖表/目标表 或其下的字段
const insertTables = (data) => {
    const sceneIds = ref([])
    const scenes = reactive({});
    // 提取参数
    data.forEach((unit) => {
        const sceneId = unit.dbLink + '||' + unit.dbBase;
        unit.name = unit.dbTable + '.' + unit.dbField;
        console.log('sceneId:', sceneId, scenes[sceneId])
        if(scenes?.[sceneId] === undefined){
            sceneIds.value.push(sceneId)
            const fields = ref([])
            fields.value.push(unit)
            scenes[sceneId] = fields.value;
        }else {
            scenes[sceneId].push(unit)
        }
    })
    sceneIds.value.forEach((unit) => {
      const fieldId = unit.split('||')[0];
      const fieldName = unit.split('||')[1];
      currentTableAttribution.top = currentTableAttribution.top + 20;
      currentTableAttribution.left = currentTableAttribution.left + currentTableAttribution.width + 10;
      const sceneOne = reactive({
          id: fieldId,
          name: fieldName,
          number: 1,
          fields: scenes[unit],
          top: currentTableAttribution.top,
          left: currentTableAttribution.left,
          width: currentTableAttribution.width,
          height: currentTableAttribution.height
      })
      addTableOperate(sceneOne);
    })
    cancelCheckLeft();
};

const manualRefLeft = ref();

const cancelCheckLeft = () => {
  manualRefLeft.value.hide()
};

const updateNumber = (options) => {
    let element = document.getElementById(options.id);
    options.number = Number(element.value);
    return options;
}

const saveScene = async () => {
    const group = reactive({tables: [], lines: []})
    console.log("save scene : ", chart.value.tables)
    console.log("save lines : ", chart.value.lines)
    notify('success', '保存成功！')
    chart.value.tables.forEach((unit)=>{
        group.tables.push(updateNumber(unit.options));
    });
    chart.value.lines.forEach((unit)=>{
        const lineParams = reactive({f: unit.options.form, t: unit.options.to})
        group.lines.push(lineParams);
    });
    console.log("scene result : ", group);
    const params = reactive({
        id: node.dict.scene_id,
        type: 'scene_group',
        target: 'content',
        content: group
    })
    let {result, status, message} = await updateSceneApi(params)
    notify(status, message);
}

onBeforeUnmount(() => {
    chart.value = null;
})

const msg_id = ref();

const createSql = () => {
  console.log('createSql', node.dict);
  msg_id.value = layer.open({
      type: "page",
      title: "数据生成：设置条件",
      area: ['35%','48%'],
      content: h(ProductData, {
        scene_info: node.dict,
        cancelAction: function (){
          layer.close(msg_id.value)
        }
      })
  })
}

</script>

<style scoped>

</style>